﻿using System;
using System.Collections.Generic;
using System.Linq;
using context;
using entities;

namespace DataAccessLibrary.DAL
{
    public class SupplyDAO
    {
         private const string Success = "SUCCESS";
        private const string Fail = "FAIL: ";

        private BlueMDataContext _ctx;

        public SupplyDAO()
        {
            _ctx = new BlueMDataContext();
        }

        public List<SupplyDetail> SelectSupplyDetail(int available)
        {
            IQueryable<SupplyDetail> query = _ctx.SupplyDetails;
            if (available > -1)
            {
                query = query.Where(p => p.Available == Convert.ToBoolean(available));
            }
            return query.ToList();
        }
     
        public SupplyDetail SelectSupplyDetailByID(int id)
        {
            IQueryable<SupplyDetail> query = _ctx.SupplyDetails;
            query = query.Where(p => p.SupplyDetailID == id);
            return query.FirstOrDefault();
        }

        public List<SupplyDetail> SearchSupplyDetailByName(string name)
        {
            IQueryable<SupplyDetail> query = _ctx.SupplyDetails;
            query = query.Where(p => p.SupplyName.Contains(name));
            return query.ToList();
        }

        public string InsertSupplyDetail(SupplyDetail supplyDetail)
        {
            try
            {
                _ctx.SupplyDetails.InsertOnSubmit(supplyDetail);
                _ctx.SubmitChanges();
                return Success;
            }
            catch (Exception ex)
            {
                _ctx = new BlueMDataContext();
                return Fail + ex.Message;
            }
        }

        public string UpdateSupplyDetail(SupplyDetail supplyDetail)
        {
            try
            {
                SupplyDetail s = SelectSupplyDetailByID(supplyDetail.SupplyDetailID);
                s.SupplyName = supplyDetail.SupplyName;
                s.SupplyPrice = supplyDetail.SupplyPrice;
                s.Available = supplyDetail.Available;
                s.Unit = supplyDetail.Unit;
                _ctx.SubmitChanges();
                return Success;
            }
            catch (Exception ex)
            {
                _ctx = new BlueMDataContext();
                return Fail + ex.Message;
            }
        }
    }
}
